package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dtos.PageResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.feign.article.ArticleFeignClient;
import com.heima.feign.wemedia.wm.WmFeignClients;
import com.heima.model.article.dtos.AuthorDto;
import com.heima.model.article.enums.ApAuthorTypeEnum;
import com.heima.model.media.dtos.WmUserSaveDTO;
import com.heima.model.media.enums.WmUserStatusEnum;
import com.heima.model.user.dtos.AuthDTO;
import com.heima.model.user.dtos.UserAuthDto;
import com.heima.model.user.dtos.UserAuthListRequestParamDTO;
import com.heima.model.user.enums.ApUserAuthStatusEnum;
import com.heima.user.mapper.ApUserAuthMapper;
import com.heima.user.pojo.ApUser;
import com.heima.user.pojo.ApUserAuth;
import com.heima.user.service.ApUserAuthService;
import com.heima.user.service.ApUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * <p>
 * APP实名认证信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2023-03-22
 */
@Slf4j
@Service
public class ApUserAuthServiceImpl extends ServiceImpl<ApUserAuthMapper, ApUserAuth> implements ApUserAuthService {


    @Autowired
    ApUserService apUserService;

    @Autowired
    WmFeignClients wmUserFeignClient;

    @Autowired
    ArticleFeignClient articleAuthorFeignClient;

    /**
     * 根据用户状态分页查询App端用户认证列表
     *
     * @param authDto
     * @return
     */
    @Override
    public PageResult<UserAuthDto> findByPage(UserAuthListRequestParamDTO authDto) {
        if (authDto == null) {
            throw new LeadException(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        // 构建分页和查询条件
        Page<ApUserAuth> iPage = new Page<>(authDto.getPage(), authDto.getSize());
        LambdaQueryWrapper<ApUserAuth> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(authDto.getStatus() != null, ApUserAuth::getStatus, authDto.getStatus());

        Page<ApUserAuth> page = this.page(iPage, queryWrapper);

        List<ApUserAuth> records = page.getRecords();
        // 如果数据不存在, 抛出异常
        if (CollectionUtils.isEmpty(records)) {
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        List<UserAuthDto> userAuthDtos = BeanHelper.copyWithCollection(records, UserAuthDto.class);
        return new PageResult<>(authDto.getPage(), authDto.getSize(), page.getTotal(), userAuthDtos);
    }

    /**
     * 用户认证信息审核不通过
     *
     * @param dto
     */
    @Override
    public void authFail(AuthDTO dto) {
        // 修改用户认证信息
        this.updateAuthStatusAndReason(dto, ApUserAuthStatusEnum.AUDIT_FAILED.getCode());
    }

    /**
     * 用户认证信息审核通过
     *
     * @param dto
     */
    @Override
    public void authPass(AuthDTO dto) {
        // 修改用户认证信息
        ApUserAuth apUserAuthDB = this.updateAuthStatusAndReason(dto, ApUserAuthStatusEnum.AUDIT_SUCCESS.getCode());
        // 更新用户身份为自媒体人
        ApUser apUserDB = apUserService.getById(apUserAuthDB.getUserId());
        if (apUserDB == null) {
            log.error("无法根据ApUserId 查询到对应的DB数据! ApUerAuthId为:{}, ApUserId: {}"
                    , dto.getId()
                    , apUserAuthDB.getUserId());
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        apUserService.updateToWemediaUser(apUserDB.getId());
        // 创建自媒体账户
        Integer wmUserId = wmUserFeignClient.save(this.buildWmUserSaveDTO(apUserDB));
        // 创建作者账户
        articleAuthorFeignClient.saveAuthor(this.buildAuthorDTO(apUserDB, wmUserId));
        // 模拟 除0异常
        // int i = 1/0;
        //  TODO 回填自媒体账户中的作者id?
    }

    /**
     * 构建AuthorDTO
     *
     * @param apUserDB apUser对象
     * @param wmUserId wmUserId
     * @return
     */
    private AuthorDto buildAuthorDTO(ApUser apUserDB, Integer wmUserId) {
        AuthorDto authorDto = new AuthorDto();
        authorDto.setUserId(apUserDB.getId());
        authorDto.setWmUserId(wmUserId);
        authorDto.setType(ApAuthorTypeEnum.WEMEDIA.getCode());
        authorDto.setName(apUserDB.getName());
        return authorDto;
    }

    /**
     * 构建WmUserSaveDTO对象的方法
     *
     * @param apUser
     * @return
     */
    private WmUserSaveDTO buildWmUserSaveDTO(ApUser apUser) {
        WmUserSaveDTO wmUserSaveDTO = new WmUserSaveDTO();
        wmUserSaveDTO.setApUserId(apUser.getId());
        wmUserSaveDTO.setName(apUser.getName());
        wmUserSaveDTO.setPassword(apUser.getPassword());
        wmUserSaveDTO.setPhone(apUser.getPhone());
        wmUserSaveDTO.setStatus(WmUserStatusEnum.AVAILABLE.getCode());
        return wmUserSaveDTO;
    }

    /**
     * 更新身份验证状态和原因
     *
     * @param dto
     */
    private ApUserAuth updateAuthStatusAndReason(AuthDTO dto, Integer code) {

        ApUserAuth apUserAuth = this.getById(dto.getId());
        if (apUserAuth == null) {
            log.error("无法根据ApUserAuth_Id 查询到对应的DB数据! AuthId为: {}", dto.getId());
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        apUserAuth.setId(dto.getId());
        apUserAuth.setReason(dto.getMsg());
        apUserAuth.setStatus(code);

        this.updateById(apUserAuth);
        return apUserAuth;
    }
}
